package com.yang.core.config;

import com.yang.core.api.RestClientInterceptor;
import com.yang.core.model.RequestContext;
import com.yang.core.model.ResponseContext;
import com.yang.core.model.ExceptionContext;
import com.yang.core.config.RestClientProperties.Auth.OAuth2;
import lombok.extern.slf4j.Slf4j;

/**
 * OAuth2认证拦截器
 */
@Slf4j
public class OAuth2AuthenticationInterceptor implements RestClientInterceptor {

    private final OAuth2 oauth2Config;

    public OAuth2AuthenticationInterceptor(OAuth2 oauth2Config) {
        this.oauth2Config = oauth2Config;
        log.info("初始化OAuth2认证拦截器，Token端点: {}", oauth2Config.getTokenUri());
    }

    @Override
    public void preRequest(RequestContext context) {
        // 添加OAuth2认证头
        String token = getAccessToken();
        if (token != null && !token.isEmpty()) {
            context.setHeader("Authorization", "Bearer " + token);
            log.debug("添加OAuth2认证头");
        }
    }

    @Override
    public void postResponse(ResponseContext context) {
        // 处理OAuth2响应
    }

    @Override
    public void onError(ExceptionContext context) {
        // 处理OAuth2错误
        if (isAuthenticationError(context)) {
            log.warn("OAuth2认证失败，可能需要刷新令牌");
        }
    }

    /**
     * 获取访问令牌
     */
    private String getAccessToken() {
        // 简化实现
        return "oauth2-access-token-demo";
    }

    /**
     * 检查是否为认证错误
     */
    private boolean isAuthenticationError(ExceptionContext context) {
        return context.getException().getMessage() != null
            && context.getException().getMessage().contains("401");
    }
}